package leetcode_core.leetcode_2;

class ListNode {
      int val;
      ListNode next;
      ListNode() {}
      ListNode(int val) { this.val = val; }
      ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}
public class AddTwoNumbers {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        //逆序存储的节点,可以新开一个链表来存储
        ListNode head = new ListNode();
        ListNode ans = head;
        int carry = 0;//进位值初始时设置为0
        while (l1!=null || l2!=null){
            int num1 = l1 == null?0:l1.val;
            int num2 = l2 == null?0:l2.val;
            int thisDigit = carry + num1 + num2;
            //处理进位的问题
            carry = thisDigit>=10?thisDigit/10:0;
            System.out.println(carry);
            thisDigit = thisDigit>=10?(thisDigit-10):thisDigit;
            head.val = thisDigit;
            l1 = l1 == null?null:l1.next;
            l2 = l2 == null?null:l2.next;
            if(l1 == null && l2 == null){
                if(carry > 0){
                    head.next = new ListNode(carry);
                }else{
                    head.next = null;
                }
                break;
            }
            head.next = new ListNode();
            head = head.next;
        }
        return ans;
    }

}
